package cc.mrbird.febs.payment.service.impl;

import cc.mrbird.febs.common.entity.QueryRequest;
import cc.mrbird.febs.pay.enums.ALiTradeState;
import cc.mrbird.febs.payment.entity.PaymentInfo;
import cc.mrbird.febs.payment.mapper.PaymentInfoMapper;
import cc.mrbird.febs.payment.service.IPaymentInfoService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.beans.factory.annotation.Autowired;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 支付记录 Service实现
 *
 * @author Mr.Yang
 * @date 2022-08-11 13:50:49
 */
@Slf4j
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements IPaymentInfoService {

    @Autowired
    private PaymentInfoMapper paymentInfoMapper;

    @Override
    public IPage<PaymentInfo> findPaymentInfos(QueryRequest request, PaymentInfo paymentInfo) {
        LambdaQueryWrapper<PaymentInfo> queryWrapper = new LambdaQueryWrapper<>();
        // TODO 设置查询条件
        Page<PaymentInfo> page = new Page<>(request.getPageNum(), request.getPageSize());
        return this.page(page, queryWrapper);
    }

    @Override
    public List<PaymentInfo> findPaymentInfos(PaymentInfo paymentInfo) {
        LambdaQueryWrapper<PaymentInfo> queryWrapper = new LambdaQueryWrapper<>();
        // TODO 设置查询条件
        return this.baseMapper.selectList(queryWrapper);
    }

    @Override
    @Transactional
    public synchronized void createPaymentInfo(PaymentInfo paymentInfo) {
        log.info("插入支付记录：{}", paymentInfo);
        this.save(paymentInfo);
    }

    @Override
    public String getTransactionId(String orderSn) {
        int a = this.baseMapper.selectCount(new LambdaQueryWrapper<PaymentInfo>().eq(PaymentInfo::getOrderNo, orderSn));
        String format = String.format("%03d", a);
        return orderSn + format;
    }

    /**
     * 订单号查询最后一个订单记录
     *
     * @param orderSn
     * @return
     */
    @Override
    public PaymentInfo getPaymentInfoByOrderSn(String orderSn) {
        return paymentInfoMapper.selectOne(new LambdaQueryWrapper<PaymentInfo>()
                .eq(PaymentInfo::getOrderNo, orderSn)
                .orderByDesc(PaymentInfo::getCreateTime)
                .last("limit 1"));
    }

    /**
     * 修改支付宝支付记录
     *
     * @param paymentInfo
     * @param params
     */
    @Override
    public synchronized void updatePaymentInfoForALiPay(PaymentInfo paymentInfo, Map<String, String> params) {
        Gson gson = new Gson();
        paymentInfo.setContent(gson.toJson(params, Map.class));
        paymentInfo.setUpdateTime(new Date());
        log.info("修改支付记录：{}", paymentInfo);
        if (StringUtils.equals(paymentInfo.getTradeState().trim(), ALiTradeState.WAIT_BUYER_PAY.getType())) {
            paymentInfo.setTradeState(ALiTradeState.TRADE_SUCCESS.getType());
            paymentInfoMapper.updateById(paymentInfo);
        }
    }


    @Override
    public PaymentInfo close(String orderSn) {
        paymentInfoMapper.update(new PaymentInfo()
                        .setTradeState(ALiTradeState.TRADE_CLOSED.getType()).setUpdateTime(new Date()),
                new LambdaUpdateWrapper<PaymentInfo>().eq(PaymentInfo::getOrderNo, orderSn));
        return null;
    }


    @Override
    public void cron() {

    }


    @Override
    @Transactional
    public void updatePaymentInfo(PaymentInfo paymentInfo) {
        this.saveOrUpdate(paymentInfo);
    }

    @Override
    @Transactional
    public void deletePaymentInfo(PaymentInfo paymentInfo) {
        LambdaQueryWrapper<PaymentInfo> wrapper = new LambdaQueryWrapper<>();
        // TODO 设置删除条件
        this.remove(wrapper);
    }
}
